import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { Row, Col, List, Image, InputNumber, Button, Empty, message } from 'antd'
import { DeleteFilled } from '@ant-design/icons'
import { getCartItems, delProductToCart, updateProductToCart } from '@/api/cart'
import { typeCartItem } from '@/types/cart'
import { $confirm, showLoading, hideLoading } from '@/register/globalFun'
import './index.scss'

const Cart = () => {
  const [cartItems, setCartItems] = useState<typeCartItem[]>([])

  useEffect(() => {
    loadCartItems()
  }, [])

  /**
   * 加载购物车内容
   */
  const loadCartItems = async() => {
    try {
      showLoading()
      const res = await getCartItems()

      setCartItems(res.data)
      console.log(res.data[ 0 ])
    } catch (err) {
      console.log(err)
    }
    hideLoading()
  }

  /**
   * 删除购物车
   * @param cart 删除的购物车
   */
  const removeCart = (cart:typeCartItem) => {
    $confirm('确认删除该商品？', async() => {
      delProductToCart(cart._id)
      const i = cartItems.findIndex(item => item._id === cart._id)
      const temp = JSON.parse(JSON.stringify(cartItems))

      temp.splice(i, 1)
      console.log(cartItems, i, temp)
      setCartItems(temp)
      message.info('已删除')
    })
  }

  const updateCart = async(cart:typeCartItem) => {
    await updateProductToCart({
      qty: cart.qty,
      cartId: cart._id
    })
    message.success('修改数量成功')
  }

  return (
    <div className="cart-list">
      <h2>我的购物车</h2>
      {
        cartItems.length === 0
          ? (<Empty
            description={
              <span>
                购物车为空, <Link to="/">点击返回首页</Link>
              </span>
            }/>)
          : (
            <Row
              align="top"
              gutter={[30, 0]}
            >
              <Col span={16}>
                {
                  cartItems.map((item:typeCartItem) => (
                    <Row
                      align="middle"
                      className="cart-list-item"
                      gutter={30}
                      key={item._id}
                    >
                      <Col>
                        <Image
                          src={item.product.image}
                          width={120}
                        />
                      </Col>
                      <Col flex={1}>
                        <h3>{item.product.name}</h3>
                      </Col>
                      <Col>
                        <strong>￥{item.product.price * item.qty}</strong>
                      </Col>
                      <Col>
                        <InputNumber
                          defaultValue={item.qty}
                          disabled={item.product.countInStock === 0}
                          max={item.product.countInStock}
                          min={1}
                          onBlur={() => { updateCart(item) }}
                          onChange={(num:number) => {
                            item.qty = num
                          }}
                        />
                      </Col>
                      <Col>
                        <Button
                          danger
                          icon={<DeleteFilled />}
                          onClick={() => removeCart(item)}
                          shape="circle"
                          type="primary"
                        />
                      </Col>
                    </Row>
                  ))
                }
              </Col>
              <Col
                className="to-pay"
                span={7}
              >
                <div className="item">
                  <h2>共计({cartItems.reduce((sum:number, item:typeCartItem) => sum + item.qty, 0)})个产品</h2>
                </div>
                <div className="item">
                    ￥{cartItems.reduce((sum:number, item:typeCartItem) => sum + (item.qty * item.product.price), 0)}
                </div>
                <Button
                  className="pay-btn"
                  size="large"
                  type="primary"
                >
                  <Link to={'/shipping'}>去支付</Link>
                </Button>
              </Col>
            </Row>
          )
      }
    </div>
  )
}

export default Cart
